<?php

namespace App\Admin\Forms;

use App\Admin\Repositories\ProjectAgreement as AppProjectAgreement;
use App\Jobs\ExportAgreementLogJob;
use App\Jobs\JobQueue;
use App\Models\ExpenseType;
use App\Models\Project;
use App\Models\ProjectAgreement;
use App\Models\User;
use App\Support\Data;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExportAgreementForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public $elementId = 'export-custom';

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        if ($input['id'] == null) {
            return $this->response()->error('未勾选协议');
        }

        array_unshift($input['column'], 'user_id');
        // 去除数据库中不存在的字段
        $input['column'] = array_diff($input['column'], ['beforeTaxAmount', 'tax']);
        
        $agreementList = ProjectAgreement::whereIn('id', explode(',', $input['id']))
            // ->select('id', 'project_id')
            // ->get()
            ->pluck('project_id')
            ->toarray();
        if (!empty($agreementList)) {
            $project = Project::where('id', $agreementList[0])->first();
            if (empty($project->project_sn)) {
                return $this->response()->error('请完善项目编号后导出');
            }
        }
        if (count(array_unique($agreementList)) > 1) {
            // if (count($agreementList) > 1) {
            return $this->response()->error('只能导出同一个项目编号下的一批协议');
        }

        $fields = '';
        foreach ($input['column'] as $key) {
            switch ($key) {
                case 'active_time': // 处理特殊字段
                    foreach (['active_time_begin', 'active_time_end'] as $temp) {
                        $fields .= "`" . $temp . "`,";
                    }
                    break;
                default:
                    $fields .= "`" . $key . "`,";
                    break;
            }
        }
        $fields = substr($fields, 0, -1);

        // $sql = "select " . $fields . " from
        //         (
        //             select a.*,
        //             p.project_name, p.project_sn, p.project_code, p.active_name, p.sponsor,
        //             p.company_short, p.is_contract, p.status as project_status
        //             from tuofu.project_agreement as a, tuofu.project as p
        //             where a.project_id = p.id and a.project_id in (" . $agreementList[0] . ")
        //         )
        //         as t";
        // and a.status = 1 and a.pay_status = 1

        $sql = "select " . $fields . " from
                (
                    select a.*,
                    p.project_name, p.project_sn, p.project_code, p.active_name, p.sponsor,
                    p.company_short, p.is_contract, p.status as project_status
                    from tuofu.project_agreement as a, tuofu.project as p
                    where a.project_id = p.id and a.id in (" . $input['id'] . ")
                )
                as t";

        $result = DB::select($sql);

        if (empty($result)) {
            return $this->response()->error('没有可导出的数据, 请检查协议审核状态');
        }

        $result = json_encode($result);

        $result = collect(json_decode($result, true));

        // 从新添加数据库中不存在的字段
        $input['column'][] = 'beforeTaxAmount';
        $input['column'][] = 'tax';

        $filterFields = $input['column'];

        foreach ($filterFields as $key => $val) {
            $transfields[] = admin_trans('agreement-manage.fields.' . $val);
        }

        $modifiedCollection = $result->map(function ($item, $key) use ($transfields) {

            // 计算税前金额
            list($tax, $beforeTaxAmount) = Data::getTaxRate($item['fee_type_value']);
            $item['beforeTaxAmount'] = $beforeTaxAmount;
            // 计算税额
            list($tax, $beforeTaxAmount) = Data::getTaxRate($item['fee_type_value']);
            $item['tax'] = $tax;

            if (!empty($item['user_id'])) {
                $user = User::find($item['user_id']);
                if (isset($item['id_card']) || empty($item['id_card'])) {
                    $item['id_card'] = $user->id_number ?? '未完善';
                }

                if (isset($item['mobile']) || empty($item['mobile'])) {
                    $item['mobile'] = $user->phone ?? '未完善';
                }
            }


            if (isset($item['fee_type_key'])) {
                $item['fee_type_key'] = ExpenseType::find($item['fee_type_key'])->title ?? '未知';
            }
            if (isset($item['pay_status'])) {
                $payStatus = AppProjectAgreement::getPayStatus();
                $item['pay_status'] = $payStatus[$item['pay_status']];
            }
            if (isset($item['audit_global_status'])) {
                $audit_global_status = [1 => '协议审核', 2 => '劳务审核'];
                $item['audit_global_status'] = $audit_global_status[$item['audit_global_status']];
            }
            if (isset($item['audit_first'])) {
                $audit_global_status = [0 => '待审核', 1 => '通过', -1 => '驳回'];
                $item['audit_first'] = $audit_global_status[$item['audit_first']];
            }

            if (isset($item['audit_log'])) {
                $log = json_decode($item['audit_log'], true);
                $audit_global_status = [1 => '协议审核', 2 => '劳务审核'];
                $audit_status = [1 => '审核通过', -1 => '驳回'];
                foreach ($log as $key => &$val) {
                    $val['audit_global_status'] = $audit_global_status[$val['audit_global_status']];
                    if (isset($val['audit_status'])) {
                        $val['audit_status'] = isset($audit_status[$val['audit_status']]) ? $audit_status[$val['audit_status']] : '';
                    } else {
                        $val['audit_status'] = '';
                    }
                }
                // $item['audit_log'] = implode(',', $log);
                $item['audit_log'] = json_encode($log);
            }

            return array_combine($transfields, array_values($item));
        });

        // todo excel导出
        try {

            $filePath = app()->storagePath() . DIRECTORY_SEPARATOR . $input['file_name'] . '.xlsx';
            $status = \Dcat\EasyExcel\Excel::export($modifiedCollection)->store($filePath);
            // todo 只有财务角色的导出记录才做留痕
            if ($status && Admin::user()->isRole('finance')) {
                ExportAgreementLogJob::dispatch($result, Admin::user(), Project::find($agreementList[0]), $input['file_name'])->onQueue(JobQueue::EXPORT);
            }
        } catch (\Exception $e) {
            Log::error('协议数据导出失败!', ['msg' => $e->getTraceAsString()]);
            return $this->response()->error('导出失败!');
        }

        return $this->response()->download('/download?cmd=export-agreement&filePath=' . $filePath);

        // return $this->response()->download($filePath);
    }



    /**
     * Build a form here.
     */
    public function form()
    {

        $this->checkbox('column', '字段')
            ->canCheckAll()
            ->default(['id', 'project_id', 'user_auth_name', 'bank_card', 'bank_name', 'bank_addr', 'id_card', 'mobile', 'fee_type_key', 'fee_type_value', 'active_name', 'beforeTaxAmount', 'tax'])
            ->options($this->payload['column'])
            ->required();
        $this->text('file_name', '文件命名')->value("datalist-" . date('YmdHis'))->required();
        // 设置隐藏表单，传递用户id
        $this->hidden('id')->attribute('id', 'reset-password-id');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function
    default()
    {
        return [];
    }
}
